package com.fms.kccc.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.util.Log;

import com.fms.kccc.task.PostTask;
import com.google.android.gcm.GCMRegistrar;

public class NotificationUtils {
	public static void register(Context context, String regId) {
		GCMRegistrar.setRegisteredOnServer(context, true);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Common.Variable.PARAMETER_REG_ID,
				regId));
		PostTask reg = new PostTask(Common.RequestURL.REG_NOTIFICATION_URL,
				params);
		reg.execute();
	}

	public static void unregister(Context context, String regId) {
		GCMRegistrar.setRegisteredOnServer(context, false);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Common.Variable.PARAMETER_REG_ID,
				regId));
		PostTask reg = new PostTask(Common.RequestURL.UNREG_NOTIFICATION_URL,
				params);
		reg.execute();
	}

	public static void setupNotification(Context context) {
		ConnectionDetector cd = new ConnectionDetector(context);
		if (!cd.isConnectingToInternet()) {
			Log.i("kccc", "No internet connection");
			return;
		}
		GCMRegistrar.checkDevice(context);
		GCMRegistrar.checkManifest(context);

		// Get GCM registration id
		final String regId = GCMRegistrar.getRegistrationId(context);

		// Check if regid already presents
		if (regId.equals("")) {
			// Registration is not present, register now with GCM
			GCMRegistrar.register(context, Common.Variable.SENDER_ID);
			Log.i("kccc", "Already registered with GCM");
		} else {
			// Device is already registered on GCM
			if (GCMRegistrar.isRegisteredOnServer(context)) {
				// Skips registration.
				Log.i("kccc", "regId");
			} else {
				register(context, regId);
			}
		}
	}
}
